<!--
 * @Description: 机票行程信息管理
 * @Version: 2.0
 * @Autor: 许国辉
 * @Date: 2022-10-26 08:21:01
 * @LastEditors: 许国辉
 * @LastEditTime: 2025-02-19 15:56:26
-->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="customHeader"> 导出表格 </a-button>
        <a-button type="primary" @click="allExport"> 导出表111 </a-button>
        <!-- <a-button type="primary" @click="exportData"> 导出表222 </a-button> -->
      </template>
    </BasicTable>
  </div>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref, toRaw } from 'vue';
  import dayjs from 'dayjs';
  import { getCarJourneyByParams } from '/@/api/travelItinerary/carItineraryAPI';
  import { Tabs } from 'ant-design-vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import { columns, searchFormSchema } from './carItineraryData';
  import { useDrawer } from '/@/components/Drawer';
  import { jsonToSheetXlsx } from '/@/components/Excel';
  import { JourneyCarModel } from '/@/api/travelItinerary/model/journey/JourneyCarModel';
  // import { exportExcel } from '/@/utils/exportExcel';
  import * as XLSX from 'xlsx'; //这是vue3导入XLSX的方法
  import FileSaver from 'file-saver';
  import XLSXStyle from 'xlsx-style-vite';

  export default defineComponent({
    components: {
      [Tabs.name]: Tabs,
      [Tabs.TabPane.name]: Tabs.TabPane,
      BasicTable,
    },
    setup() {
      const journeyCarModel = ref<JourneyCarModel>();
      const visible = ref<boolean>(false);
      let api = ref(getCarJourneyByParams);
      let title = ref('普通订单');
      const [register] = useDrawer();
      const [registerTable, { reload, getDataSource, setColumns, getForm }] = useTable({
        api,
        pagination: { pageSize: 10 },
        columns: columns,
        formConfig: {
          schemas: searchFormSchema,
          fieldMapToTime: [['fieldTime', ['deptDateStart', 'deptDateEnd'], 'YYYY-MM-DD']],
        },
        showTableSetting: true,
        tableSetting: { fullScreen: true },
        striped: false,
        useSearchForm: true,
        bordered: true,
        showIndexColumn: false,
      });
      const hideModal = () => {
        visible.value = false;
      };
      function send(record: JourneyCarModel) {
        journeyCarModel.value = toRaw(record);
        console.log(journeyCarModel);
        visible.value = true;
      }

      function handleSuccess() {
        reload();
      }
      async function tabChange() {
        setColumns(columns);
        title.value = '普通订单';
        api.value = getCarJourneyByParams;
        await getForm().submit;
        reload();
      }
      function customHeader() {
        let header1 = {
          orderNo: '订单号',
          childChannelName: '用车渠道',
          accountNo: '工号',
          reserveName: '预定人',
          departAddress: '出发地',
          arriveAddress: '目的地',
          createTime: '创建时间',
          departureTime: '到达日期',
          licensePlate: '车牌号',
          carBrand: '车辆品牌',
          realFee: '总金额',
        };
        interface JourneyData {
          orderNo: string;
          childChannelName: string;
          accountNo: string;
          reserveName: string;
          departAddress: string;
          arriveAddress: string;
          createTime: string;
          departureTime: string;
          licensePlate: string;
          carBrand: string;
          realFee: string;
        }
        let orderArr: JourneyData[] = [];
        for (let k = 0; k < toRaw(getDataSource()).length; k++) {
          let orderdata = ref<JourneyData>({
            orderNo: '订单号',
            childChannelName: '用车渠道',
            accountNo: '工号',
            reserveName: '预定人',
            departAddress: '出发地',
            arriveAddress: '目的地',
            createTime: '创建时间',
            departureTime: '到达日期',
            licensePlate: '车牌号',
            carBrand: '车辆品牌',
            realFee: '总金额',
          });
          orderdata.value!.orderNo = toRaw(getDataSource())[k].orderNo;
          orderdata.value!.childChannelName = toRaw(getDataSource())[k].childChannelName;
          orderdata.value!.accountNo = toRaw(getDataSource())[k].accountNo;
          orderdata.value!.reserveName = toRaw(getDataSource())[k].reserveName;
          orderdata.value!.departAddress = toRaw(getDataSource())[k].departAddress;
          orderdata.value!.arriveAddress = toRaw(getDataSource())[k].arriveAddress;
          orderdata.value!.createTime = toRaw(getDataSource())[k].createTime;
          orderdata.value!.departureTime = toRaw(getDataSource())[k].departureTime;
          orderdata.value!.licensePlate = toRaw(getDataSource())[k].licensePlate
            ? toRaw(getDataSource())[k].licensePlate
            : '-';
          orderdata.value!.carBrand = toRaw(getDataSource())[k].carBrand;
          orderdata.value!.realFee = toRaw(getDataSource())[k].realFee;

          orderArr.push(orderdata.value);
        }
        jsonToSheetXlsx({
          data: orderArr,
          header: header1,
          filename: '用车信息.xlsx' + dayjs(new Date()).format('YYYY- MM - DD') + '.xlsx',
          json2sheetOpts: {
            // 指定顺序
            // header: ['name', 'id'],
          },
        });
      }
      const reportsDataTitle = [
        {
          ProjectNo: '21-10093',
          ProjectName: '',
          EasNo: '2021052',
          EasName: '算单',
          CashflowRemark: '',
        },
      ];

      const reportsDataFlow = [
        {
          ProjectNo: '21-10093',
          ProjectName: '',
          EasNo: '2021052',
          EasName: '算单',
          CashflowRemark: '',
        },
      ];

      const reportsDataCash = [
        {
          ProjectNo: '21-10093',
          ProjectName: '',
          EasNo: '2021052',
          EasName: '算单',
          CashflowRemark: '',
        },
      ];
      // 全部導出
      const allExport = async () => {
        var Cash = reportsDataCash; //表格
        var CashFlow = reportsDataFlow; //表格
        //展示的顺序，把data中对象的属性按照你想要的顺序排放就可以了，我这里把id移到了第一列展示
        const header = ['ProjectNo', 'ProjectName', 'EasNo', 'EasName', 'CashflowRemark'];
        //展示的名称
        const headerDisplay = {
          ProjectNo: 'S栏',
          ProjectName: 'h栏',
          EasNo: 'e栏',
          EasName: 'e_1栏',
          CashflowRemark: 't栏',
        };
        const Title = [headerDisplay, ...reportsDataTitle];
        // const Cash = [headerDisplay, ...reportsDataTitle];
        // const CashFlow = [headerDisplay, ...reportsDataTitle];
        var sheet1 = XLSX.utils.json_to_sheet(Title, { header: header, skipHeader: true });
        var sheet2 = XLSX.utils.json_to_sheet(Cash);
        var sheet3 = XLSX.utils.json_to_sheet(CashFlow);

        var wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, sheet1, '月度统计报表');
        XLSX.utils.book_append_sheet(wb, sheet2, 'Cash');
        XLSX.utils.book_append_sheet(wb, sheet3, 'Cashflow');

        setExlStyle(wb['Sheets']['月度统计报表']); // 设置列宽 字号等
        //(wb['Sheets']['月度统计报表']['!merges'], wb['Sheets']['月度统计报表']);
        // let wbout = XLSXStyle.write(wb, { type: 'file', bookType: 'xlsx' });
        let wbout = XLSXStyle.write(wb, { bookType: 'xlsx', bookSST: false, type: 'binary' });
        // const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' });
        // FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), `aaaa.xlsx`);
        FileSaver.saveAs(
          new Blob([s2ab(wbout)], {
            type: 'application/octet-stream',
          }),
          '全部人员.xlsx',
        );
        // this.openDownloadDialog(workbookBlob, 'Cashflow报告_' + nowDate + '.xlsx');
      };

      // 工具方法
      function s2ab(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
      }

      const setExlStyle = (data) => {
        let borderAll = {
          //单元格外侧框线
          top: {
            style: 'thin',
          },
          bottom: {
            style: 'thin',
          },
          left: {
            style: 'thin',
          },
          right: {
            style: 'thin',
          },
        };
        data['!cols'] = [];
        for (let key in data) {
          // console.log(key)
          if (data[key] instanceof Object) {
            data[key].s = {
              border: borderAll,
              alignment: {
                horizontal: 'center', //水平居中对齐
                vertical: 'center',
              },
              font: {
                sz: 11,
              },
              bold: true,
              numFmt: 0,
            };
            data['!cols'].push({ wpx: 115 });
          }
        }
        return data;
      };
      // const addRangeBorder = (range, ws) => {
      //   let cols = [
      //     'A',
      //     'B',
      //     'C',
      //     'D',
      //     'E',
      //     'F',
      //     'G',
      //     'H',
      //     'I',
      //     'J',
      //     'K',
      //     'L',
      //     'M',
      //     'N',
      //     'O',
      //     'P',
      //     'Q',
      //     'R',
      //     'S',
      //     'T',
      //     'U',
      //     'V',
      //     'W',
      //     'X',
      //     'Y',
      //     'Z',
      //   ];
      //   if (range) {
      //     range.forEach((item) => {
      //       console.log(item);
      //       let style = {
      //         s: {
      //           border: {
      //             top: { style: 'thin' },
      //             left: { style: 'thin' },
      //             bottom: { style: 'thin' },
      //             right: { style: 'thin' },
      //           },
      //         },
      //       };
      //       // 处理合并行
      //       for (let i = item.s.c; i <= item.e.c; i++) {
      //         ws[`${cols[i]}${Number(item.e.r) + 1}`] =
      //           ws[`${cols[i]}${Number(item.e.r) + 1}`] || style;
      //         // 处理合并列
      //         for (let k = item.s.r + 2; k <= item.e.r + 1; k++) {
      //           ws[cols[i] + k] = ws[cols[k] + item.e.r] || style;
      //         }
      //       }
      //     });
      //   }

      //   return ws;
      // };

      onMounted(() => {
        //employeeData.initEmployeeData();
      });

      return {
        tabChange,
        registerTable,
        handleSuccess,
        register,
        send,
        customHeader,
        allExport,
        visible,
        hideModal,
        journeyCarModel,
      };
    },
  });
</script>
